package com.daervin.svc.parser.hot;

import com.daervin.svc.common.dto.hot.JiKiPeDiaData;
import com.daervin.svc.common.dto.hot.JiKiPeDiaResult;
import com.daervin.svc.common.utils.HttpClientUtil;
import com.daervin.svc.common.utils.JsonUtil;
import com.daervin.svc.dal.model.Hot;
import com.daervin.svc.dal.model.HotItem;
import com.daervin.svc.service.IHotService;
import okhttp3.Headers;
import okhttp3.Response;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.daervin.svc.common.constants.HotSiteEnum.JI_KI_PE_DIA;

/**
 * @author daervin
 * @date 2019/12/11
 */
public class JiKiPeDiaRun implements Runnable {
    private IHotService service;

    public JiKiPeDiaRun(IHotService service) {
        this.service = service;
    }

    @Override
    public void run() {
        try {
            Map<String, String> param = new HashMap<>();
            Map<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json, text/plain, */*");
            headers.put("Host", "api.jikipedia.com");
            headers.put("Origin", "https://jikipedia.com");
            headers.put("Referer", "https://jikipedia.com/hotsearch");
            headers.put(" User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER");
            Response response = HttpClientUtil.post(JI_KI_PE_DIA.TOPIC_URL, JsonUtil.toString(param), Headers.of(headers));
            if (response == null || !response.isSuccessful() || response.body() == null) {
                return;
            }
            String responseData = response.body().string();
            JiKiPeDiaResult result = JsonUtil.toObject(responseData, JiKiPeDiaResult.class);
            if (result == null || CollectionUtils.isEmpty(result.getData())) {
                return;
            }
            List<HotItem> hotItemList = new ArrayList<>();
            for (JiKiPeDiaData data : result.getData()) {
                if (StringUtils.isEmpty(data.getPhrase())) {
                    continue;
                }
                hotItemList.add(new HotItem(JI_KI_PE_DIA.ID, data.getPhrase(), "https://jikipedia.com/search?phrase=" + data.getPhrase(), 0L));
            }
            if (CollectionUtils.isEmpty(hotItemList)) {
                return;
            }
            if (service != null) {
                service.addItems(hotItemList, new Hot(JI_KI_PE_DIA, hotItemList.size()));
            }
        } catch (Exception e) {
            System.err.println("JiKiPeDiaRun" + e.getMessage());
        }
    }
}
